﻿using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using net.xBei.Models.json;

namespace net.xBei.Filters {
    /// <summary>
    /// 输入参数校验过滤器
    /// </summary>
    public class ValidationFilter : IAsyncResultFilter {
        /// <inheritdoc/>
        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next) {
            if (!context.ModelState.IsValid) {
                var errorResponse = new ResponseData<object> {
                    Success = false,
                    Code = 400,
                    Message = "输入参数错误",
                    Data = context.ModelState.Where(x => x.Value?.Errors.Count > 0)
                                             .Select(err => new {
                                                 param = err.Key,
                                                 rawValue = err.Value?.RawValue,
                                                 errorMessage = err.Value?.Errors.Select(e => e.ErrorMessage)
                                             }).ToArray(),
                };
                context.Result = new BadRequestObjectResult(errorResponse);
            }
            await next();
        }
    }
}
